package cn.com.blackboard.DataModule4B2.BBDataUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import blackboard.admin.data.datasource.DataSource;
import blackboard.admin.persist.datasource.DataSourceManager;
import blackboard.admin.persist.datasource.DataSourceManagerFactory;
import blackboard.data.ValidationException;
import blackboard.persist.KeyNotFoundException;
import blackboard.persist.PersistenceException;

public class DataSourceUtil {
	private static final Logger logger = LoggerFactory.getLogger(DataSourceUtil.class);

	private static DataSourceManager dataSourceManager = null;
	static {
		dataSourceManager = DataSourceManagerFactory.getInstance();
	}
	
	public static DataSource createDataSourceFromBatchUid(String batchUid, String descrition){
		try {
			return dataSourceManager.create(batchUid, descrition);
		} catch (PersistenceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (ValidationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	public static DataSource loadDataSourceByBatchUid(String batchUid){
		try {
			return dataSourceManager.loadByBatchUid(batchUid);
		} catch (KeyNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (PersistenceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	public static DataSource createOrLoad(String batchUid, String descrition ){
		try {
			logger.info("loading datasource with "+batchUid);
			return dataSourceManager.loadByBatchUid(batchUid);
		} catch (KeyNotFoundException e) {
			try {
				logger.info("datasource with "+batchUid+" loaded failed, tring to create one");
				return dataSourceManager.create(batchUid, descrition);
			} catch (PersistenceException e1) {
				logger.info("create datasource with "+batchUid+" persistence failed");
				return null;
			} catch (ValidationException e1) {
				logger.info("create datasource with "+batchUid+" validation failed");
				return null;
			}
		} catch (PersistenceException e) {
			logger.info("load datasource with "+batchUid+" persistence failed");
			return null;
		} 
	}
}
